package qc.module.cms.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.ResourceStatusFlagEnum;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.module.cms.dto.swipper.EditFlagDto;
import qc.module.cms.dto.swipper.SwipperDto;
import qc.module.cms.entity.CategorySwipper;
import qc.module.cms.mapper.CategorySwipperMapper;
import qc.module.cms.repository.CategorySwipperRepository;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * CategorySwipperService
 *
 * @author QuCheng Tech
 * @since 2023/5/29
 */
@Service
public class CategorySwipperService {
    private CategorySwipperRepository repository;

    @Autowired
    public void setCategorySwipperRepository(CategorySwipperRepository repository) {
        this.repository = repository;
    }

    /***
     * 获取指定栏目中所有轮播图，包含横隔；不管状态
     *
     * @param categoryId 栏目ID
     * @return java.util.List<qc.module.cms.dto.swipper.SwipperDto>
     * @author QuCheng Tech
     * @since 2023/10/25
     */
    public List<SwipperDto> getCategoryAllSwippers(int categoryId) {
        LambdaQueryWrapper<CategorySwipper> wrapper = new LambdaQueryWrapper<>();
        //指定查询内容
        wrapper.select(CategorySwipper::getId, CategorySwipper::getCid, CategorySwipper::getFid, CategorySwipper::getFlag, CategorySwipper::getOdr, CategorySwipper::getTitle, CategorySwipper::getArticleid, CategorySwipper::getGroupid, CategorySwipper::getIscategory);
        //匹配栏目
        wrapper.eq(CategorySwipper::getCid, categoryId);
        //排序：先按分组ID、再按排序号、ID降序（后加入的在前）、最后按标题
        wrapper.orderByAsc(CategorySwipper::getGroupid);
        wrapper.orderByAsc(CategorySwipper::getOdr);
        wrapper.orderByDesc(CategorySwipper::getId);
        wrapper.orderByAsc(CategorySwipper::getTitle);
        List<CategorySwipper> categorySwippers = repository.selectList(wrapper);
        if (categorySwippers.size() > 0x0) {
            return CategorySwipperMapper.MAPPER.toDtoList(categorySwippers);
        }
        return null;
    }

    /***
     * 获取指定栏目中有效的轮播图和横隔，轮播图指定数量，横隔为所有有效
     *
     * @param categoryId 栏目ID
     * @param count 轮播图数量，小于1时表示查询所有
     * @return java.util.List<qc.module.cms.dto.swipper.SwipperDto>
     * @author QuCheng Tech
     * @since 2023/10/25
     */
    public List<SwipperDto> getCategoryValidSwippersAndSeptums(int categoryId, int count) {
        List<SwipperDto> swippers = getCategoryValidSwippers(categoryId, count);
        List<SwipperDto> septums = getCategoryValidSeptums(categoryId);
        if (swippers != null && swippers.size() > 0x0) {
            if (septums != null && septums.size() > 0x0) {
                //合并轮播图和横隔List
                return Stream.of(swippers, septums).flatMap(Collection::stream).collect(Collectors.toList());
            } else {
                return swippers;
            }
        } else {
            return septums;
        }
    }

    /***
     * 获取指定栏目中有效的显示轮播图，不包含横隔
     *
     * @param categoryId 栏目ID
     * @param count 轮播图数量，小于1时表示查询所有
     * @return java.util.List<qc.module.cms.dto.swipper.SwipperDto>
     * @author QuCheng Tech
     * @since 2023/10/25
     */
    public List<SwipperDto> getCategoryValidSwippers(int categoryId, int count) {
        LambdaQueryWrapper<CategorySwipper> wrapper = new LambdaQueryWrapper<>();
        //指定查询内容
        wrapper.select(CategorySwipper::getId, CategorySwipper::getCid, CategorySwipper::getFid, CategorySwipper::getFlag, CategorySwipper::getOdr, CategorySwipper::getTitle, CategorySwipper::getArticleid, CategorySwipper::getGroupid, CategorySwipper::getIscategory);
        //匹配栏目
        wrapper.eq(CategorySwipper::getCid, categoryId);
        wrapper.eq(CategorySwipper::getGroupid, 0x0);
        wrapper.eq(CategorySwipper::getFlag, ResourceStatusFlagEnum.NORMAL);
        //判断是否有查询数量
        if (count > 0x0) {
            wrapper.last("limit " + count);
        }
        //排序：先按ID（后加入的在前）、再按排序号
        wrapper.orderByDesc(CategorySwipper::getId);
        wrapper.orderByAsc(CategorySwipper::getOdr);

        List<CategorySwipper> categorySwippers = repository.selectList(wrapper);
        if (categorySwippers.size() > 0x0) {
            return CategorySwipperMapper.MAPPER.toDtoList(categorySwippers);
        }
        return null;
    }

    /***
     * 获取指定栏目中有效的横隔
     *
     * @param categoryId 栏目ID
     * @return java.util.List<qc.module.cms.dto.swipper.SwipperDto>
     * @author QuCheng Tech
     * @since 2023/10/25
     */
    public List<SwipperDto> getCategoryValidSeptums(int categoryId) {
        LambdaQueryWrapper<CategorySwipper> wrapper = new LambdaQueryWrapper<>();
        //指定查询内容
        wrapper.select(CategorySwipper::getId, CategorySwipper::getCid, CategorySwipper::getFid, CategorySwipper::getFlag, CategorySwipper::getOdr, CategorySwipper::getTitle, CategorySwipper::getArticleid, CategorySwipper::getGroupid, CategorySwipper::getIscategory);
        //匹配栏目
        wrapper.eq(CategorySwipper::getCid, categoryId);
        wrapper.ne(CategorySwipper::getGroupid, 0x0);
        wrapper.eq(CategorySwipper::getFlag, ResourceStatusFlagEnum.NORMAL);
        //排序：先按分组ID、再按排序号、ID降序（后加入的在前）、最后按标题
        wrapper.orderByAsc(CategorySwipper::getGroupid);
        wrapper.orderByAsc(CategorySwipper::getOdr);
        wrapper.orderByDesc(CategorySwipper::getId);
        wrapper.orderByAsc(CategorySwipper::getTitle);

        List<CategorySwipper> categorySwippers = repository.selectList(wrapper);
        if (categorySwippers.size() > 0x0) {
            return CategorySwipperMapper.MAPPER.toDtoList(categorySwippers);
        }
        return null;
    }

    /**
     * 新增轮播图
     *
     * @param dto:新增轮播图信息
     * @return String 新增成功返回null
     * @author QcCheng Tech
     * @date 2023/7/17
     */
    public String add(SwipperDto dto) {
        if (dto == null)
            return QCUnifyReturnValue.Warn("对象不能为空");
        //DTO转换为Entity
        CategorySwipper en = CategorySwipperMapper.MAPPER.SwipperDtoToEntity(dto);
        //生成id
        en.setId(genereateId());
        if (repository.insert(en) < 0x1)
            return QCUnifyReturnValue.Warn("保存轮播图失败");
        return QCUnifyReturnValue.Success();

    }

    /**
     * 修改轮播图信息
     *
     * @param dto: 修改信息
     * @return String 成功返回null，失败返回错误信息
     * @author QcCheng Tech
     * @date 2023/7/17
     */
    public String update(SwipperDto dto) {
        if (dto == null)
            return QCUnifyReturnValue.Warn("对象不能为空");
        //判断轮播图是否存在
        if (!hasIdExist(dto.getId())) {
            return QCUnifyReturnValue.Warn("轮播图不存在");
        }
        //DTO转换为Entity
        CategorySwipper en = CategorySwipperMapper.MAPPER.SwipperDtoToEntity(dto);
        if (repository.updateById(en) < 0x0)
            return QCUnifyReturnValue.Warn("修改轮播图失败");
        return QCUnifyReturnValue.Success();
    }

    /***
     * 更新指定轮播图ID的封面图片ID和标题，数据不再进行验证
     *
     * @param swipperId 轮播图ID
     * @param cover 封面图片ID
     * @param title 标题
     * @return java.lang.String
     * @author QuCheng Tech
     * @since 2023/10/25
     */
    public void update(int swipperId, int cover, String title) {
        LambdaUpdateWrapper<CategorySwipper> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(CategorySwipper::getFid, cover);
        wrapper.set(CategorySwipper::getTitle, title);

        wrapper.eq(CategorySwipper::getId, swipperId);

        repository.update(null, wrapper);
    }

    /**
     * 删除轮播图，isLogicDelete：是否为逻辑删除，为true表示逻辑删除--修改记录标记，为false表示物理删除--从数据库表中删除记录
     *
     * @param id 轮播图id
     * @return 成功放回null，失败返回错误信息
     * @author QcCheng Tech
     * @date 2023/10/15
     */
    public String delete(int id, boolean isLogicDelete) {
        //判断轮播图是否存在
        if (!hasIdExist(id)) {
            return QCUnifyReturnValue.Warn("轮播图不存在");
        }
        if (isLogicDelete) {
            LambdaUpdateWrapper<CategorySwipper> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(CategorySwipper::getId, id);
            wrapper.set(CategorySwipper::getFlag, ResourceStatusFlagEnum.DELETED);
            if (repository.update(null, wrapper) < 0x0)
                return QCUnifyReturnValue.Warn("删除失败");
        } else {
            if (repository.deleteById(id) < 0x1)
                return QCUnifyReturnValue.Warn("删除失败");
        }
        return QCUnifyReturnValue.Success();
    }

    /**
     * 启用或禁用轮播图，修改轮播图状态值
     *
     * @param dto: 设置信息
     * @return String 成功返回null,失败返回错误信息
     * @author QcCheng Tech
     * @date 2023/10/23
     */
    public String editFlag(EditFlagDto dto) {
        CategorySwipper en = getEntity(dto.getId());
        if (en == null)
            return QCUnifyReturnValue.Warn("指定轮播图不存在");
        LambdaUpdateWrapper<CategorySwipper> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(CategorySwipper::getId, dto.getId());
        if (dto.getFlagStatus()) {
            wrapper.set(CategorySwipper::getFlag, ResourceStatusFlagEnum.NORMAL);
        } else {
            wrapper.set(CategorySwipper::getFlag, ResourceStatusFlagEnum.DISABLE);
        }
        repository.update(null, wrapper);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 根据指定id获取轮播图信息
     *
     * @param id:轮播图id
     * @return CategorySwipper
     * @author QcCheng Tech
     * @date 2023/10/23
     */
    public CategorySwipper getEntity(int id) {
        LambdaQueryWrapper<CategorySwipper> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CategorySwipper::getId, id);

        return repository.selectOne(wrapper);
    }

    /***
     * 根据指定文章id获取轮播图信息，如果有多个仅返回最新1个
     *
     * @param articleId 文章ID
     * @param groupId 轮播图分组ID
     * @return qc.module.cms.entity.CategorySwipper
     * @author QuCheng Tech
     * @since 2023/10/25
     */
    public CategorySwipper getEntityByArticleId(int articleId, int groupId) {
        LambdaQueryWrapper<CategorySwipper> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CategorySwipper::getArticleid, articleId);
        wrapper.eq(CategorySwipper::getGroupid, groupId);
        wrapper.orderByDesc(CategorySwipper::getId);

        return repository.selectOne(wrapper);
    }

    /**
     * 判断数据库中指定轮播图信息是否存在
     *
     * @param id: 轮播图id
     * @return boolean 存在返回true,不存在返回false
     * @author QcCheng Tech
     * @date 2023/10/11
     */
    boolean hasIdExist(int id) {
        LambdaQueryWrapper<CategorySwipper> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(CategorySwipper::getId);
        wrapper.eq(CategorySwipper::getId, id);
        CategorySwipper categorySwipper = repository.selectOne(wrapper);
        if (categorySwipper != null)
            return true;
        return false;

    }

    /**
     * 生成记录ID，获取数据库表中的最大记录ID+1
     *
     * @return 生成记录ID
     * @author QuCheng Tech
     * @since 2023/5/28
     */
    Integer genereateId() {
        Integer maxRecordId = getMaxId();
        return maxRecordId + 1;
    }

    /**
     * 获取数据库表中的最大ID值，没有记录时返回0
     *
     * @return 返回数据库表中的最大ID值
     * @author QuCheng Tech
     * @since 2023/5/28
     */
    Integer getMaxId() {
        LambdaQueryWrapper<CategorySwipper> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(CategorySwipper::getId);
        wrapper.orderByDesc(CategorySwipper::getId);
        CategorySwipper categorySwipper = repository.selectOne(wrapper);
        if (categorySwipper != null)
            return categorySwipper.getId();
        return 0x0;
    }
}
